package db.swing1;

import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.swing.JFrame;

import de.dnb.basics.applicationComponents.DbProperties;
import de.dnb.basics.applicationComponents.DbUtils;

public final class MetaDataQueryFrameExample {
	public static void main(final String[] args) throws SQLException {
		Connection connection = null;
		// Hier kein ARM, da keine Freigabe am Blockende erlaubt, s.u.
		try {

			DbProperties properties = new DbProperties("D:/db/db.properties");
			String url = properties.getUrl()
					+ ";ifexists=false;create=false;readonly=true";
			connection = DriverManager.getConnection(url,
					properties.getUserName(), properties.getPassword());
			final PreparedStatement preparedStatement = connection
					.prepareStatement("SELECT * FROM sw WHERE name LIKE ?",
							ResultSet.TYPE_SCROLL_INSENSITIVE,
							ResultSet.CONCUR_READ_ONLY);
			final MetaDataQueryFrame frame = new MetaDataQueryFrame(
					preparedStatement);
			frame.setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
			frame.setSize(500, 300);
			frame.setVisible(true);
			// Trick: Zugriff auf die nicht finale Connection
			// in der inneren Klasse ermöglichen
			final Connection connectionReference = connection;
			frame.addWindowListener(new WindowAdapter() {
				@Override
				public void windowClosing(final WindowEvent event) {
					DbUtils.safeCloseStatement(preparedStatement);
					DbUtils.safeCloseConnection(connectionReference);
					frame.setVisible(false);
					frame.dispose();
				}
			});
			// initial "Execute SQL" ausführen
			frame.executeSqlSelect();
		} catch (final SQLException e) {
			DbUtils.safeCloseConnection(connection);
			throw e;
		} finally {
			// Freigabe der Ressourcen hier nicht möglich, da
			// zu früh, GUI läuft ja noch
			// DbUtils.safeCloseConnection(connection);
		}
	}
}